<template>
	<view class="wrapper address-edit">
		<!--表单-->
		<view class="form">
			<uni-forms
				:modelValue="form"
				ref="formRef"
				:label-width="80"
				:rules="rules">
				<uni-forms-item label="收货人" name="contacts" required>
					<uni-easyinput
						type="text"
						:inputBorder="false"
						primaryColor="#e3230e"
						v-model="form.contacts"
						placeholder="请输入收货人" />
				</uni-forms-item>
				<uni-forms-item label="手机号码" name="phone" required>
					<uni-easyinput
						type="text"
						:inputBorder="false"
						primaryColor="#e3230e"
						v-model="form.phone"
						placeholder="请输入手机号码" />
				</uni-forms-item>
				<uni-forms-item label="所在地区" name="addr" required>
					<uni-data-picker
						v-model="regionCode"
						placeholder="请选择所在地区"
						popup-title="请选择所在地区"
						:localdata="setStore.region"
						:border="false"
						:map="{text:'label',value:'value'}"
						@change="onChangeAddr">
					</uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="详细地址" name="detail" required>
					<uni-easyinput
						type="text"
						:inputBorder="false"
						primaryColor="#e3230e"
						v-model="form.detail"
						placeholder="街道、楼道号等" />
				</uni-forms-item>
				<uni-forms-item label="标签" name="addrLabel">
					<uni-easyinput
						type="text"
						:inputBorder="false"
						primaryColor="#e3230e"
						v-model="form.addrLabel"
						maxlength="5"
						placeholder="请输入您的门店简称，最多5个字。" />
				</uni-forms-item>
				<uni-forms-item label="设置默认地址" name="defaultFlag" :label-width="120">
					<view class="form-checked main-flex">
						<u-switch
							v-model="form.defaultFlag"
							:inactiveValue="0"
							:activeValue="1"
							activeColor="#e3230e"
							size="20" ></u-switch>
					</view>
				</uni-forms-item>
			</uni-forms>
		</view>
		<button class="ty-button ty-button-confirm form-submit" :disabled="isSubmit" :loading="isSubmit" @click="submit">保存</button>
	</view>
</template>

<script setup>
import { computed, ref, watch, watchEffect } from 'vue';
import { onReady, onLoad, onReachBottom, onShow, onHide } from '@dcloudio/uni-app';
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
import { editAddress } from "@/api/app_api/user"
import { throttle, debounce, test, sleep } from '@/uni_modules/uview-plus'
import modal from '@/plugins/modal'

	const userStore = useUserStore()
	const setStore = useSetStore()
	
	const id = ref('')
	onLoad((options) => {
		if (options.id) {
			uni.setNavigationBarTitle({
				title: '编辑地址'
			})
			id.value = options.id
			getDetail()
		}
	})
	
	// 获取详情
	const info = ref(null)
	const getDetail = () => {
		const detail = uni.getStorageSync('setAddr') || ''
		if (detail) {
			info.value = detail
			form.value = {
				contacts: detail.contacts,
				phone: detail.phone,
				addr: detail.addr,
				detail: detail.detail,
				addrLabel: detail.addrLabel,
				regionCode: detail.regionCode,
				defaultFlag: detail.defaultFlag
			}
			if (setStore.region.length > 0) {
				setRegionCode()
			}
		} else {
			uni.$u.toast('获取详情失败')
			uni.navigateBack({
				delta: 1
			})
		}
	}
	
	const setRegionCode = () => {
		const firstFilter = setStore.region.filter(item => item.value == info.value?.regionCode)
		const secondFilter = firstFilter?.[0]?.children.filter(item => info.value.addr.indexOf(item.label) > -1) || []
		const thirdFilter = secondFilter?.[0]?.children.filter(item => info.value.addr.indexOf(item.label) > -1) || []
		regionCode.value = thirdFilter?.[0]?.value || ''
	}
	
	watch(() => setStore.region, (nval, oval) => {
		if (nval.length > 0) {
			setRegionCode()
		}
	})
	
	// 表单
	const formRef = ref(null)
	const form = ref({
		contacts: '',
		phone: '',
		addr: '',
		detail: '',
		addrLabel: '',
		regionCode: '',
		defaultFlag: 0
	})
	// 表单验证
	const rules = ref({
		contacts: {
			rules: [{
				required: true,
				errorMessage: '请输入收货人'
			}]
		},
		phone: {
			rules: [{
				required: true,
				errorMessage: '请输入手机号码'
			}, {
				validateFunction: function (rule,value,data,callback) {
					if (!test.mobile(value)) {
						callback('请输入正确手机号码')
					}
					return true
				}
			}]
		},
		addr: {
			rules: [{
				required: true,
				errorMessage: '请选择所在地区'
			}]
		},
		detail: {
			rules: [{
				required: true,
				errorMessage: '请输入详细地址'
			}]
		},
	})
	
	// 选择区域
	const regionCode = ref(userStore.regionCode || '')
	const onChangeAddr = (e) => {
		form.value.regionCode = e.detail.value?.[0].value
		form.value.addr = e.detail.value.reduce((prev, cur, index, arr) => {
			return prev + cur.text
		}, '')
	}
	
	// 表单提交
	const isSubmit = ref(false)
	const submit = () => {
		formRef.value.validate().then(formRes => {
			isSubmit.value = true
			const params = {
				...form.value
			}
			if (id.value) {
				params.id = id.value
			}
			editAddress(params).then(res => {
				uni.$u.toast(res.msg)
				uni.$u.sleep(1000).then(() => {
					isSubmit.value = false
					uni.navigateBack({
						delta: 1
					})
					uni.$emit('refresh');  // 触发刷新事件
				})
			}).catch(err => {
				isSubmit.value = false
			})
		})
	}
	
	onReady(() => {
		formRef.value.setRules(rules.value)
	})
	
</script>

<style lang="scss">
	.address-edit {
		padding: 20rpx;
	}
	.form {
		padding: 0rpx 32rpx;
		border-radius: 20rpx;
		background-color: #ffffff;
		&-checked {
			height: $input-height;
			justify-content: flex-end;
		}
		&-submit {
			height: $button-height;
			padding: 0;
			margin: 0;
			margin-top: 40rpx;
			font-size: 32rpx;
		}
	}
	:deep(.uni-data-tree) {
		width: calc(646rpx - 80px);
		height: $input-height;
		.uni-data-tree-input {
			height: 100%;
			.input-value {
				height: 100%;
			}
		}
	}
</style>
